<template>
	<div class="login">
		<div class="bgPic"><img src="../../../public/static/img/login-img/bg.png" alt=""></div>
		<div class="logo_bg"><img src="../../../public/static/img/login-img/logo.png" alt=""></div>
		<div class="draw"><img src="../../../public/static/img/login-img/draw.png" alt=""></div>
		<div class="welcomeTxt">
			<h2>Hi,</h2>
			<h2>欢迎登录{{VUE_APP_TYPE_NAME}}平台</h2>
		</div>
		<div class="login-container">
			<!-- logo -->
			<!-- <div class="logo">
        <img src="../../../static/img/logo-sm.png" alt />
        <div class="img">
          <img :src="'../../../static/oem/'+oemConfig.activeOem+'/logo-sm.png'" alt>
        </div>
        <h1 class="title">商户平台</h1>
      </div> -->

			<!-- 登录表单 -->
			<div v-loading="codeNoLoading" class="login-form">
				<el-tabs v-model="tabName" class="login-tab">
					<!-- 微信登录 -->
					<el-tab-pane label="扫码登录" name="wx" class="login-wx">
						<div v-loading="wxLoading" class="qrcode">
							<img class="qrcode_logo" src="../../../public/static/img/login-img/qrcode_logo.png" alt="">
							<img v-if="qrcodeUrl" :src="qrcodeUrl">
							<div v-if="isQrcodeExpire" class="refresh" @click="getQrCode">
								<p>
									二维码已失效
									<br>
									点击刷新
								</p>
							</div>
						</div>
						<div class="tips">打开微信扫一扫登录</div>
					</el-tab-pane>

					<!-- 账号登录 -->
					<el-tab-pane label="账户登录" name="user">
						<el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left">
							<el-form-item prop="username">
								<!-- <span class="svg-container svg-container_login"><svg-icon icon-class="s-i-user" /></span> -->
								<el-input v-model="loginForm.username" name="username" type="text"
									placeholder="请输入用户名" />
							</el-form-item>
							<el-form-item prop="password">
								<!-- <span class="svg-container svg-container_login"><svg-icon icon-class="s-i-password" /></span> -->
								<el-input v-model="loginForm.password" :type="pwdType" name="password"
									placeholder="请输入密码" @keyup.enter.native="login">
									<!-- <i slot="suffix" class="el-input__icon el-icon-view" @click="showPwd" /> -->
								</el-input>
							</el-form-item>
							<el-form-item>
								<el-button :loading="btnLoading" type="primary" class="login-btn"
									@click.native.prevent="login">登 录</el-button>
							</el-form-item>
						</el-form>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>

		<!-- 登录弹窗 -->
		<dialog-list ref="dialogList" :code-no="codeNo" :scope="scope" />
	</div>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import {
		wxLoginQrCode,
		checkWxLoginState
	} from '@/api/login'
	import {
		setToken
	} from '@/utils/auth'
	import DialogList from './components/DialogList'
	import {
		wxLogin
	} from '@/api/login'
	export default {
		name: 'Login',
		components: {
			DialogList
		},
		data() {
			/**
			 * 表单校验方法相关
			 */
			const validateUsername = (rule, value = '', callback) => {
				if (value === '') {
					callback(new Error('请输入用户名'))
				} else {
					callback()
				}
			}
			const validatePass = (rule, value = '', callback) => {
				if (value === '') {
					callback(new Error('请输入密码'))
				} else {
					callback()
				}
			}
			return {
				VUE_APP_TYPE_NAME: '',
				/**
				 * 表单校验字段相关
				 */
				loginRules: {
					username: [{
						validator: validateUsername,
						trigger: 'blur'
					}],
					password: [{
						validator: validatePass,
						trigger: 'blur'
					}]
				},
				loginForm: {
					username: '',
					password: ''
				},
				// 配置
				tabName: 'user',
				scope: 'business',
				redirect: undefined,
				pwdType: 'password',
				// 状态
				wxLoading: false, // 微信qrcode loading
				btnLoading: false, // 登录按钮loading
				codeNoLoading: false, // 通过codeNo登录
				isQrcodeExpire: false, // qrcode 是否过期
				isStopChecked: false, // 是否终止轮询
				// 数据
				codeNo: '', // 二维码no
				qrcodeUrl: '' // 微信登录二维码
			}
		},
		computed: {
			...mapGetters(['oemConfig'])
		},
		watch: {
			$route: {
				handler: function(route) {
					this.redirect = route.query && route.query.redirect
				},
				immediate: true
			},
			tabName(val) {
				if (val === 'wx') {
					this.getQrCode()
				} else {
					this.isStopChecked = true
				}
			}
		},
		created() {
			// 设置流量预警开关是否打开
			localStorage.setItem('flowWarnTag', 'open')
			console.log('process.env.VUE_APP_TYPE_NAME------',process.env.VUE_APP_TYPE_NAME)
			this.VUE_APP_TYPE_NAME = process.env.VUE_APP_TYPE_NAME === 'xianghui' ? '商户' : '公域'
		},
		mounted: function() {
			// 判断是否是其它平台进来
			if (this.$route.query.hasOwnProperty('codeNo')) {
				const params = {}
				params.codeNo = this.$route.query.codeNo
				params.scope = this.scope
				this.codeNoLoading = true
				wxLogin(params)
					.then(res => {
						// 保存token
						setToken(res.data)
						this.$store.state.user.token = res.data
						// 跳转
						this.$router.push({
							path: '/'
						})
					})
					.catch(() => {
						this.codeNoLoading = false
					})
			}
		},
		methods: {
			/**
			 * 获取数据
			 */
			// 获取微信登陆二维码
			getQrCode() {
				this.isStopChecked = false
				this.wxLoading = true
				wxLoginQrCode({
						scope: this.scope
					})
					.then(res => {
						this.codeNo = res.data.codeNo
						this.qrcodeUrl = res.data.qrcodeUrl
						console.log('获取微信登陆二维码', res)
						// 关闭刷新提示
						this.isQrcodeExpire = false
						// 检查状态
						this.checkQrcodeState(this.codeNo)
					})
					.finally(() => {
						this.wxLoading = false
					})
			},

			// 检查微信登陆二维码状态
			checkQrcodeState(codeNo) {
				const params = {}
				params.codeNo = codeNo
				params.scope = this.scope
				checkWxLoginState(params)
					.then(res => {
						switch (res.data.state) {
							case 0:
								// 0.未登陆未失效,轮询状态 2000ms
								if (!this.isStopChecked) {
									const timerId = setTimeout(() => {
										clearTimeout(timerId)
										this.checkQrcodeState(codeNo)
									}, 2000)
								}
								break
							case 1:
								// 1.登录成功,判断一个还是多个用户
								// if (res.data.hasOwnProperty('userList')) {
								//   this.$refs.dialogList.open(res.data.userList).then(() => {
								//     this.isStopChecked = false
								//     this.getQrCode()
								//   })
								// } else {
								//   // 保存token
								//   setToken(res.data.token)
								//   this.$store.state.user.token = res.data.token
								//   // 跳转
								//   this.$router.push({
								//     path: '/'
								//   })
								// }

								// 保存token
								setToken(res.data.token)
								this.$store.state.user.token = res.data.token
								// 跳转
								this.$router.push({
									path: '/'
								})
								break
							case 2:
								// 2.失效,显示提示
								this.isQrcodeExpire = true
								break
						}
					})
					.catch(err => {})
					.finally(() => {})
			},
			/**
			 * 按钮组
			 */
			// 登录
			login() {
				this.$refs.loginForm.validate(valid => {
					if (valid) {
						this.btnLoading = true
						this.$store
							.dispatch('Login', this.loginForm)
							.then(() => {
								sessionStorage.removeItem(`${this.loginForm.username}`)
								const routerQuery = localStorage.getItem('routerQuery') ? JSON.parse(
									localStorage.getItem('routerQuery')) : {}
								this.$router.push({
									path: this.redirect || '/',
									query: routerQuery
								})
							})
							.finally(() => {
								this.btnLoading = false
							})
					} else {
						return false
					}
				})
			},

			// 显示隐藏密码
			showPwd() {
				if (this.pwdType === 'password') {
					this.pwdType = ''
				} else {
					this.pwdType = 'password'
				}
			}
		}
	}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	.login {
		position: fixed;
		height: 100%;
		width: 100%;
		background-color: white;

		.bgPic {
			width: 100%;
			height: 100%;
			position: fixed;
			z-index: 1;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.logo_bg {
			width: 5%;
			position: fixed;
			top: 20.7%;
			left: 17%;
			z-index: 1;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.draw {
			width: 43%;
			position: fixed;
			bottom: 20%;
			left: 0;
			z-index: 1;
		}

		.welcomeTxt {
			position: fixed;
			top: 20vh;
			left: 23.5%;
			z-index: 1;

			h2 {
				font-weight: 500;
				font-size: 2vw;
				margin: 0;
				margin-bottom: 1vh;
			}
		}

		&-container {
			position: absolute;
			left: 0;
			right: 0;
			// width: 460px;
			max-width: 100%;
			margin: 120px auto;
			z-index: 2;
		}

		.logo {
			width: 800px;
			height: 100px;
			margin: 0px auto;
			line-height: 100px;
			text-align: center;

			.img {
				vertical-align: top;
				display: inline-block;
				width: 100px;
				height: 100px;
				margin-right: 10px;
			}

			.title {
				display: inline-block;
				margin: 0;
				font-size: 40px;
				font-weight: 600;
				color: #fefefe;
			}
		}

		/* 微信登录 */
		&-wx {
			.qrcode {
				position: relative;
				width: 60%;
				height: 60%;
				margin: 0 auto;
				margin-top: 15%;

				img {
					// border: 1px solid #eee;
					// box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
				}

				.qrcode_logo {
					position: absolute;
					top: 37%;
					left: 37%;
					width: 25%;
					height: 25%;
					background-color: white;
					border-radius: 10px;
				}
			}

			.refresh {
				display: flex;
				justify-content: center;
				align-items: center;
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				line-height: 30px;
				background: #000;
				font-size: 18px;
				opacity: 0.8;
				color: #fff;
				text-align: center;
				cursor: pointer;
			}

			.tips {
				margin-top: 10%;
				font-size: 14px;
				text-align: center;
				color: $dark-font-color;
			}
		}

		/* 用户登录 */
		&-form {
			width: 25%;
			margin-top: 6%;
			padding: 3% 3%;
			border-radius: 20px;
			background: #fff;
			box-shadow: 0 0 30px #ffead0;
			float: right;
			margin-right: 18%;

			.svg-container {
				position: absolute;
				z-index: 2;
				height: 20px;
				left: 10px;
				top: 10px;
				text-align: center;
				color: #909399;

				&_login {
					font-size: 20px;
				}
			}

			.el-input__icon {
				font-size: 18px;
				height: 208px;
			}

			.el-input {
				display: inline-block;
				height: 5vh;
			}

			.login-btn {
				margin-top: 15%;
				width: 100%;
				padding: 1.8vh 0;
				font-size: 1vw;
				background-color: #ffb72f;
				border: none;
				border-radius: 8px;
			}
		}
	}
</style>

<style rel="stylesheet/scss" lang="scss">
	.login {
		&-tab {
			.el-tabs__nav {
				left: 50%;
				width: 100%;
				transform: translateX(-50%) !important;
			}

			.el-tabs__header {
				margin-bottom: 0;
				background-color: #fff;

				.el-tabs__nav-wrap.is-scrollable {
					padding: 0;
				}

				.el-tabs__nav-next,
				.el-tabs__nav-prev {
					display: none;
				}

				.el-tabs__item {
					width: 50%;
					height: 4.5vh;
					line-height: 31px;
					font-size: 1vw;
					color: #b3b3b3;
					font-weight: bold;
					text-align: center;
					padding: 0;
				}

				.el-tabs__item.is-active {
					color: #ffb72f;
				}
			}

			.el-tabs__active-bar {
				width: 10% !important;
				height: 0.5vh;
				left: 20%;
				border-radius: 10px;
				background-color: #ffb72f;
			}

			.el-tabs__nav-wrap {
				&:after {
					height: 0;
				}
			}
		}

		.el-input {
			.el-input__inner {
				height: 100%;
				padding: 0;
				line-height: 56px;
				font-size: 18px;
				border: none;
				border-bottom: 1px solid #e0e0e0;
				border-radius: 0;
			}

			.el-input__inner:focus {
				border-color: #ffb72f;
			}
		}

		.el-form-item {
			margin-top: 5vh;

			::-webkit-input-placeholder {
				font-size: 0.8vw;
			}
		}

		.el-form-item:nth-last-child(1) {
			margin-bottom: 0;
		}

		.el-form-item__error {
			line-height: 2vh;
			font-size: 0.8vw;
		}
	}
</style>
